package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/xfio/internal/db"
)

// formatDurationSince 返回从给定时间到现在的时间差，格式化为相对时间字符串
func formatDurationSince(t time.Time) string {
	duration := time.Since(t)
	
	if duration < time.Minute {
		return fmt.Sprintf("%ds ago", int(duration.Seconds()))
	} else if duration < time.Hour {
		return fmt.Sprintf("%dm %ds ago", int(duration.Minutes()), int(duration.Seconds())%60)
	} else if duration < 24*time.Hour {
		return fmt.Sprintf("%dh %dm ago", int(duration.Hours()), int(duration.Minutes())%60)
	} else {
		return fmt.Sprintf("%dd %dh ago", int(duration.Hours())/24, int(duration.Hours())%24)
	}
}

func setupWebRoutes(r *gin.Engine, database *db.DB) {
	// 设置模板目录
	r.LoadHTMLGlob("assets/templates/*")

	// 静态文件服务
	r.Static("/static", "assets/static")

	// 主页 - 概览
	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "base.html", gin.H{
			"title":       "概览",
			"icon":        "fas fa-tachometer-alt",
			"currentPage": "dashboard",
			"assetVersion": time.Now().Unix(),
		})
	})

	// 节点管理页面
	r.GET("/workers", func(c *gin.Context) {
		// 从API获取真实数据
		originalWorkers, err := getAllWorkers(database)
		if err != nil {
			// 如果获取失败，使用空数组
			originalWorkers = []interface{}{}
		}
		
		// 处理workers，添加相对时间格式的最后心跳和注册时间字段
		var workers []interface{}
		for _, worker := range originalWorkers {
			if workerMap, ok := worker.(map[string]interface{}); ok {
				// 处理最后心跳时间
				if lastHeartbeatStr, exists := workerMap["last_heartbeat"].(string); exists {
					if lastHeartbeat, err := time.Parse(time.RFC3339, lastHeartbeatStr); err == nil {
						workerMap["last_heartbeat_relative"] = formatDurationSince(lastHeartbeat)
					} else {
						workerMap["last_heartbeat_relative"] = "N/A"
					}
				} else {
					workerMap["last_heartbeat_relative"] = "N/A"
				}
				
				// 处理注册时间 - 尝试解析时间字符串并格式化为相对时间
				if createdAtStr, exists := workerMap["created_at"].(string); exists {
					parsedTime, err := time.Parse(time.RFC3339, createdAtStr)
					if err != nil {
						// 如果标准格式不工作，尝试其他可能的格式
						parsedTime, err = time.Parse("2006-01-02T15:04:05Z", createdAtStr)
					}
					
					if err == nil {
						workerMap["created_at_relative"] = formatDurationSince(parsedTime)
					} else {
						// 解析失败时显示原始时间戳
						workerMap["created_at_relative"] = createdAtStr
					}
				} else {
					workerMap["created_at_relative"] = "N/A"
				}
				workers = append(workers, workerMap)
			}
		}
		
		// 计算统计数据
		totalWorkers := len(workers)
		onlineWorkers := 0
		offlineWorkers := 0
		healthyWorkers := 0
		warningWorkers := 0
		errorWorkers := 0
		
		// 遍历workers计算各种数量
		for _, worker := range workers {
			if workerMap, ok := worker.(map[string]interface{}); ok {
				// 计算在线/离线数量
				if status, exists := workerMap["status"]; exists {
					if statusStr, ok := status.(string); ok && statusStr == "online" {
						onlineWorkers++
					} else {
						offlineWorkers++
					}
				}
				
				// 计算心跳健康状态数量
				if heartbeatStatus, exists := workerMap["heartbeat_status"]; exists {
					if statusStr, ok := heartbeatStatus.(string); ok {
						switch statusStr {
						case "healthy":
							healthyWorkers++
						case "warning":
							warningWorkers++
						case "error":
							errorWorkers++
						}
					}
				}
			}
		}
		
		c.HTML(http.StatusOK, "workers.html", gin.H{
			"title":          "节点管理",
			"icon":           "fas fa-server",
			"currentPage":    "workers",
			"data":           workers,
			"totalWorkers":   totalWorkers,
			"onlineWorkers":  onlineWorkers,
			"offlineWorkers": offlineWorkers,
			"healthyWorkers": healthyWorkers,
			"warningWorkers": warningWorkers,
			"errorWorkers":   errorWorkers,
			"assetVersion":   time.Now().Unix(),
		})
	})

	// 测试用例管理页面
	r.GET("/test-cases", func(c *gin.Context) {
		c.HTML(http.StatusOK, "test-cases.html", gin.H{
			"title":       "测试用例",
			"icon":        "fas fa-file-code",
			"currentPage": "test-cases",
			"assetVersion": time.Now().Unix(),
		})
	})

	// 创建测试用例页面
	r.GET("/test-cases/create", func(c *gin.Context) {
		c.HTML(http.StatusOK, "test-case-basic-create.html", gin.H{
			"title":       "创建测试用例",
			"icon":        "fas fa-plus-circle",
			"currentPage": "test-cases",
			"assetVersion": time.Now().Unix(),
		})
	})

	// 任务管理页面
	r.GET("/tasks", func(c *gin.Context) {
		c.HTML(http.StatusOK, "tasks.html", gin.H{
			"title":       "任务管理",
			"icon":        "fas fa-tasks",
			"currentPage": "tasks",
			"assetVersion": time.Now().Unix(),
		})
	})

	// 结果分析页面
	r.GET("/results", func(c *gin.Context) {
		c.HTML(http.StatusOK, "base.html", gin.H{
			"title":       "结果分析",
			"icon":        "fas fa-chart-bar",
			"currentPage": "results",
			"assetVersion": time.Now().Unix(),
		})
	})
}